import React, { Component } from 'react';
import '../styles/Register.css'
import { goLogin, goRegister } from '../api/login'
class Register extends Component {
    constructor(props) {
        super(props)
        this.state = {
            username: '',
            password: '',
            flag:false
        }
    }
    //判断数据有变化时才更新，提高性能
    shouldComponentUpdate(nextProps, nextState) {
        if (JSON.stringify(this.state) == JSON.stringify(nextState)) {
            return false
        } else {
            return true
        }
    }
    //让表单受控
    changeIPT(e) {
        this.setState({
            [e.target.name]: e.target.value
        })
    }
    //点击小锁子显示密码
    eye() {
        this.setState({
           flag:!(this.state.flag)
        })
    }
    //发送注册请求
    Register() {
        if (this.state.username.trim() != '' && this.state.password.trim() != '') {
            if (/^1[3456789]\d{9}$/.test(this.state.username)) {
                if (/^\S*(?=\S{6,})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])\S*$/.test(this.state.password)) {
                    goRegister({ phone: this.state.username, pass: this.state.password }).then((res) => {
                        console.log(res);
                        alert('注册成功，请登录')
                    })
                } else {
                    alert('密码格式有误')
                }
            } else {
                alert('手机号格式有误')
            }
        } else {
            alert('请输入内容')
        }
    }
    //去登录
    goLogin(){
        this.props.history.push('/login')
    }
    render() {
        return (
            <div className='register'>
                <div className="lbox">
                    <i className='iconfont icon-gerenzhongxin'></i>

                    <input type="text" placeholder='请输入用户名'
                        name='username' value={this.state.username}
                        onChange={(e) => { this.changeIPT(e) }} />

                    <i className={`iconfont ${this.state.flag?"icon-jiesuo1":"icon-jiesuo"}`} 
                    onClick={() => { this.eye() }}></i>

                    <input type={this.state.flag?'type':"password"} placeholder='请输入密码
                    'name='password' value={this.state.password}
                        onChange={(e) => { this.changeIPT(e) }} />

                    <button onClick={() => { this.Register() }}>注册</button>

                    <a href="" onClick={()=>{this.goLogin()}}>登录</a>
                </div>
            </div>
        );
    }
}

export default Register;
